//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useState } from "react";
import type { LocalRepoExtInfo } from "@/stores/localrepo";
import { useStores } from "@/hooks";
import { Form, message, Modal, Select } from "antd";
import { resolve } from "@tauri-apps/api/path";
import { exists as exist_path, removeFile } from '@tauri-apps/api/fs';
import { set_link_info } from "@/api/project_tool";

export interface LinkProjectModalProps {
    repoExtInfo: LocalRepoExtInfo;
    onClose: () => void;
}

const LinkProjectModal = (props: LinkProjectModalProps) => {
    const projectStore = useStores("projectStore");
    const localRepoStore = useStores("localRepoStore");

    const [projectId, setProjectId] = useState(props.repoExtInfo.projectId);
    const [hasChange, setHasChange] = useState(false);

    const removeLink = async () => {
        const attrPath = await resolve(props.repoExtInfo.repoInfo.path, ".linksaas.yml");
        const exist = await exist_path(attrPath);
        if (exist) {
            await removeFile(attrPath);
        }
        localRepoStore.onUpdateRepo(props.repoExtInfo.id);
        props.onClose();
        message.info("取消关联成功");
    };

    const setLink = async () => {
        await set_link_info(props.repoExtInfo.repoInfo.path, projectId);
        localRepoStore.onUpdateRepo(props.repoExtInfo.id);
        props.onClose();
        message.info("关联成功");
    };

    return (
        <Modal open title="关联项目" mask={false}
            okText="关联" okButtonProps={{ disabled: !hasChange }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onClose();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                if (projectId == "") {
                    removeLink();
                } else {
                    setLink();
                }
            }}>
            <Form>
                <Form.Item >
                    <Select value={projectId} onChange={value => {
                        setProjectId(value);
                        setHasChange(true);
                    }}>
                        <Select.Option value="">不关联项目</Select.Option>
                        {projectStore.projectList.map(item => (
                            <Select.Option key={item.project_id} value={item.project_id}>项目:{item.basic_info.project_name}</Select.Option>
                        ))}
                    </Select>
                </Form.Item>
            </Form>
        </Modal>
    );

};

export default LinkProjectModal;